﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Common;
using H2.NET.Web.Workflow.DwzCode;
using log4net;
using Ultimus.OC;
using Ultimus.WFServer;
using UServLib;
using H2.NET.Business.Core;
using H2.NET.Data.Common;

namespace H2.NET.Web.Workflow.Workflow
{
    public partial class FindAndReplaceVariables : BasePage
    {
        /// <summary>
        /// 日志记录
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        protected void Page_Load(object sender, EventArgs e)
        {
            var action = AksRequest.GetQueryStringValue("action");
            if (string.IsNullOrEmpty(action)) //默认页面加载
            {
                var processName = AksRequest.GetString("process").Trim();
                var incidentNo = AksRequest.GetInt("incident", 0);

                var filter = new TasklistFilter
                {
                    strProcessNameFilter = processName,
                    nIncidentNo = incidentNo
                };

                var taskList = new Tasklist();
                taskList.LoadFilteredTasks(filter);

                var dtTasks = new DataTable();
                dtTasks.Columns.Add("taskId");
                dtTasks.Columns.Add("taskName");

                for (var i = 0; i < taskList.GetTasksCount(); i++)
                {
                    var task = taskList.GetAt(i);
                    if (task == null)
                    {
                        continue;
                    }

                    var row = dtTasks.NewRow();
                    row["taskId"] = task.strTaskId;
                    row["taskName"] = task.strStepName + " ： " + task.strRecipientFullName;

                    dtTasks.Rows.Add(row);
                }

                gvTasks.DataSource = dtTasks;
                gvTasks.DataBind();
            }
            else if (action == "save") //form提交
            {
                var process = "";
                var incident = 0;
                var success = 0;
                var fail = 0;
                try
                {
                    var flag = false;
                    var taskId = AksRequest.GetFormString("tid");
                    var isReplaceAll = AksRequest.GetFormString("isReplaceAll");
                    var task = new Task();
                    if (task.InitializeFromTaskId(taskId))
                    {
                        process = task.strProcessName;
                        incident = task.nIncidentNo;
                    }

                    if (isReplaceAll == "true") //需要替换所有激活步骤的变量
                    {
                        var filter = new TasklistFilter
                        {
                            strProcessNameFilter = process,
                            nIncidentNo = incident,
                            nFiltersMask = Filters.nFilter_Current,
                        };

                        var taskList = new Tasklist();
                        taskList.LoadFilteredTasks(filter);
                        for (var i = 0; i < taskList.GetTasksCount(); i++)
                        {
                            var tsk = taskList.GetAt(i);
                            if (tsk != null)
                            {
                                if (ReplaceVariables(tsk))
                                {
                                    success++;
                                }
                                else
                                {
                                    fail++;
                                }
                            }
                            else
                            {
                                fail++;
                            }
                        }
                    }
                    else
                    {
                        if (ReplaceVariables(task))
                        {
                            success++;
                        }
                        else
                        {
                            fail++;
                        }
                    }

                    var incidentManageLog = new t_log_IncidentManage
                    {
                        Process = task.strProcessName,
                        Incident = task.nIncidentNo,
                        Status = true,
                        Action = "流程变量修改",
                        Description = "成功：" + success + " 失败：" + fail,
                        Creator = UserAPI.UserFullName,
                        CreateOn = DateTime.Now
                    };
                    Storage.Save(incidentManageLog);
                }
                catch (Exception ex)
                {
                    // 记录错误日志
                    var errorLog = new t_log_IncidentManage
                    {
                        Process = process,
                        Status = false,
                        Action = "流程变量修改",
                        Description = "ERROR:" + ex.Message,
                        Creator = UserAPI.UserFullName,
                        Incident = incident,
                        CreateOn = DateTime.Now
                    };
                    Storage.Save(errorLog);

                    Logger.Error(ex.Message);
                    ErrorMsg(ex.Message);
                }

                ShowMessage("成功：" + success + "，失败：" + fail);
            }
        }

        private bool ReplaceVariables(Task task)
        {
            var description = string.Empty;
            Variable[] variables;
            var strError = "";
            task.GetAllTaskVariables(out variables, out strError);

            if (variables != null && strError == "")
            {
                //循环所有变量，如果有form提交就修改值
                foreach (var variable in variables)
                {
                    var newValue = HttpContext.Current.Request.Form[variable.strVariableName].Trim();
                    var originalValue = variable.objVariableValue == null
                        ? ""
                        : string.Join(" ", variable.objVariableValue).Trim();
                    if (newValue != originalValue)
                    {
                        description += "[" + variable.strVariableName + "]" + originalValue + "->" + newValue +
                                       ";";
                    }

                    if (string.IsNullOrEmpty(newValue))
                    {
                        variable.objVariableValue = new object[1];
                        variable.objVariableValue[0] = "";
                    }
                    else
                    {
                        if (variable.objVariableValue == null)
                        {
                            variable.objVariableValue = new object[1];
                        }

                        var varLen = variable.objVariableValue.Length;
                        if (varLen == 1)
                        {
                            variable.objVariableValue[0] = newValue;
                        }
                        else if (varLen > 1)
                        {
                            var aryValue = newValue.Split(' ').Distinct().ToArray();
                            for (var i = 0; i < varLen; i++)
                            {
                                if (i > aryValue.Length - 1)
                                {
                                    variable.objVariableValue[i] = "";
                                }
                                else
                                {
                                    variable.objVariableValue[i] = aryValue[i];
                                }
                            }
                        }
                    }
                }

                var incidentManageLog = new t_log_IncidentManage
                {
                    Process = task.strProcessName,
                    Incident = task.nIncidentNo,
                    Status = true,
                    Action = "流程变量修改",
                    Description = task.strStepName + "：" + description,
                    Creator = UserAPI.UserFullName,
                    CreateOn = DateTime.Now
                };
                Storage.Save(incidentManageLog);

                //保存变量
                return task.Save(variables, out strError);

            }
            else
            {
                return false;
            }
        }
    }
}